/**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: BeanHelper
 * Author:   andy
 * Date:     18/1/28 上午2:20
 * Description: ${DESCRIPTION}
 * History:
 */
package org.smart4j.framework.helper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.smart4j.framework.util.ReflectionUtil;

/**
 * Bean助手类<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/28 上午2:20
 */
public class BeanHelper {

    /**
     * 定义Bean映射（用于存放Bean类与Bean实例的映射关系）
     */
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();

    // 加载获取Bean放入容器
    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class beanClass : beanClassSet) {
            Object obj = ReflectionUtil.newInstance(beanClass);
            BEAN_MAP.put(beanClass, obj);
        }
    }

    /**
     * 获取Bean映射
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    public static void putBean(Class<?> cls, Object obj) {
        BEAN_MAP.put(cls, obj);
    }

    /**
     * 获取Bean实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> cls) {
        if (!BEAN_MAP.containsKey(cls)) {
            throw new RuntimeException("can not get bean by class: " + cls);
        }
        return (T)BEAN_MAP.get(cls);
    }

}
